<template>
  <el-dialog :title="title" :visible.sync="visible" class="dialog-sm" append-to-body @close="visible = false">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" v-loading="loading">
      <el-form-item label="上级部门" prop="parent_id" v-if="form.id !== rootDept">
        <TreeSelect v-model="form.parent_id" :options="deptOptions" :normalizer="normalizer" placeholder="选择上级部门"/>
      </el-form-item>
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入部门名称" maxlength="64"/>
      </el-form-item>
      <el-form-item label="负责人" prop="leader">
        <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="32"/>
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="32"/>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="64"/>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="显示排序" prop="list_sort">
            <el-input-number v-model="form.list_sort" controls-position="right" :min="0" class="w-full"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" maxlength="250"/>
      </el-form-item>
    </el-form>
    <div class="dialog-footer slot">
      <el-button type="primary" @click="handleSubmit" :loading="submitting" :disabled="loading">确 定</el-button>
      <el-button @click="visible = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { infoDeptApi, editDeptApi, addDeptApi, selectDeptApi } from '@/api/system/dept'

export default {
  name: 'DeptForm',
  dicts: ['sys_normal_disable'],
  components: { TreeSelect },
  props: {
    value: Boolean,
    row: Object,
    moduleName: String
  },
  data() {
    return {
      title: '',
      loading: false,
      submitting: false,
      deptOptions: [],
      form: {
        name: undefined,
        parent_id: undefined,
        leader: '',
        phone: '',
        email: '',
        status: '1',
        list_sort: 10,
        remark: ''
      },
      rules: {
        parent_id: [{ required: true, message: '上级部门不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
        list_sort: [{ required: true, message: '显示排序不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
        // email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
        // phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }]
      }
    }
  },
  computed: {
    visible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    },
    rootDept() {
      return this.$store.getters.config?.root_dept_id || 0
    }
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      this.loading = true
      this.form.id = this.row?.id || undefined
      if (this.form.id) {
        this.title = '编辑' + this.moduleName
        await this.getRowData()
      } else {
        this.title = '添加' + this.moduleName
        this.form.parent_id = this.row?.parent_id || undefined
      }
      await this.getDeptOptions()
      this.loading = false
    },
    async getRowData() {
      try {
        const { info } = await infoDeptApi(this.form.id)
        this.form = this.dataToForm(this.form, info)
      } catch (error) {
        this.visible = false
      }
    },
    async handleSubmit() {
      try {
        const valid = await this.$refs.formRef.validate()
        if (!valid) return
      } catch (error) {
        return
      }
      if (this.submitting) return
      this.submitting = true
      try {
        await this.$modal.confirm('确定提交表单数据？')
        if (this.form.id) {
          await editDeptApi(this.form)
        } else {
          await addDeptApi(this.form)
        }
        this.$emit('submit')
        this.$modal.msgSuccess('操作成功')
        this.visible = false
      } catch (e) {
        this.submitting = false
      }
    },
    async getDeptOptions() {
      try {
        const { list } = await selectDeptApi()
        this.deptOptions = this.listToTree(list)
      } catch (e) {
      }
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    }
  }
}
</script>
